package cn.zhentao.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * JWT辅助工具类
 * 提供便捷的JWT操作方法
 */
@Component
public class JwtHelper {

    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 从当前请求中获取JWT令牌
     * @return JWT令牌，如果没有则返回null
     */
    public String getCurrentToken() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return null;
        }
        
        HttpServletRequest request = attributes.getRequest();
        String authHeader = request.getHeader("Authorization");
        
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        
        return null;
    }

    /**
     * 从当前请求中获取当前用户名
     * @return 用户名，如果没有则返回null
     */
    public String getCurrentUsername() {
        String token = getCurrentToken();
        if (token == null) {
            return null;
        }
        
        try {
            return jwtUtils.getUsernameFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 从当前请求中获取当前用户ID
     * @return 用户ID，如果没有则返回null
     */
    public Long getCurrentUserId() {
        String token = getCurrentToken();
        if (token == null) {
            return null;
        }
        
        try {
            return jwtUtils.getUserIdFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 验证当前请求的JWT令牌是否有效
     * @return 是否有效
     */
    public boolean isCurrentTokenValid() {
        String token = getCurrentToken();
        if (token == null) {
            return false;
        }
        
        return jwtUtils.validateToken(token);
    }

    /**
     * 检查当前请求的JWT令牌是否即将过期
     * @return 是否即将过期
     */
    public boolean isCurrentTokenNearExpiration() {
        String token = getCurrentToken();
        if (token == null) {
            return false;
        }
        
        return jwtUtils.isTokenNearExpiration(token);
    }
} 